import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { Group } from './entities/group.entity';
import { RedisService } from 'src/modules/common/services/redis.service';

@Injectable()
export class GroupCacheService {
  constructor(private readonly redisService: RedisService) {}
  private getListByStageIdKey = 'group:getListByStageId';

  @OnEvent('group.update')
  async handleGroupUpdate(payload: Group) {
    await this.deleteGroup(payload.id);
    const { stageId } = payload;
    await this.deleteListByStageId(stageId);
  }
  async getGroup(groupId: number) {
    const res = await this.redisService.get(`group:${groupId}`);
    return res ? JSON.parse(res) : null;
  }
  async setGroup(group: Group) {
    await this.redisService.set(`group:${group.id}`, JSON.stringify(group));
  }
  async deleteGroup(groupId: number) {
    await this.redisService.delete(`group:${groupId}`);
  }
  // group:getListByStageId st
  async getListByStageId(stageId: number) {
    const res = await this.redisService.get(
      `${this.getListByStageIdKey}:${stageId}`,
    );
    return res ? JSON.parse(res) : null;
  }
  async setListByStageId(stageId: number, list: Group[]) {
    await this.redisService.set(
      `${this.getListByStageIdKey}:${stageId}`,
      JSON.stringify(list),
    );
  }
  async deleteListByStageId(stageId: number) {
    await this.redisService.delete(`${this.getListByStageIdKey}:${stageId}`);
  }
  // group:getListByStageId ed
}
